package com.lovo.system.dao.impl;

import com.lovo.common.dao.BaseDao;
import com.lovo.common.model.CutPageBean;
import com.lovo.common.model.EmpBean;
import com.lovo.common.model.LogBean;
import com.lovo.system.dao.ILogDao;

import java.sql.SQLException;
import java.time.LocalDate;

/**
 * 日志管理的Dao实现类
 * @author 白德柯
 *
 */
public class LogDaoImpl extends BaseDao implements ILogDao {
    @Override
    public CutPageBean<LogBean> findByItem(int page, String startDate, String endDate) {
        String sql = "select * from sys_log";
        String conditionSql = " where 1=1 ";
        if(startDate != null && !startDate.equals("")){
            conditionSql += "AND create_date >= '"+startDate+"' ";
        }
        if(endDate != null && !endDate.equals("")){
            conditionSql += "AND create_date <= '"+endDate+"' ";
        }

        CutPageBean<LogBean> cutPageBean = new CutPageBean<>();
        this.setConnection();
        try {
            ps = con.prepareStatement(sql + conditionSql + CutPageBean.getPageSql(page));
            rs = ps.executeQuery();
            while(rs.next()){
                cutPageBean.getList().add(fill());
            }
            ps = con.prepareStatement("SELECT COUNT(*) cnt FROM ("+ sql + conditionSql +") t");
            rs = ps.executeQuery();
            rs.next();
            // 获取员工总数并设置给分页对象
            cutPageBean.setCount(rs.getInt("cnt"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.close();
        }
        return cutPageBean;
    }

    @Override
    public int add(String logInfo) {
        String sql = "INSERT INTO `crm`.`sys_log` (`create_date`, `log_info`) \n" +
                "VALUES\n" +
                "  (?, ?)";
        this.setConnection();
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, LocalDate.now());
            ps.setObject(2, logInfo);
            return ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally{
            this.close();
        }
        return 0;
    }

    private LogBean fill() throws SQLException {
        LogBean logBean = new LogBean();
        logBean.setId(rs.getInt("id"));
        if(rs.getDate("create_date") != null){
            logBean.setCreateDate(rs.getDate("create_date").toLocalDate());
        }
        logBean.setLogInfo(rs.getString("log_info"));
        return logBean;
    }

    public static void main(String[] args) {
        ILogDao logDao = new LogDaoImpl();
//        System.out.println(logDao.findByItem(1,null,"2021-10-28"));
        logDao.add("小张登录");
    }
}
